
var timer = setInterval(function() {
    // 判断postMessage是否已经可用
    if (window.postMessage.length === 3) {
        // 定位成功 & 失败
        if (pos && inArea && !isError) {
            let RnParams = {
                type: MessageParams.RECEIVE_DISTANCE,
                params: {
                    storeList: storeList,
                    inArea: inArea,
                    currentPos: currentPos
                }
            }
            window.postMessage(JSON.stringify(RnParams));
            clearInterval(timer);
            timer = null;
        } else if (isError) {
            let a1 = {
                type: MessageParams.RECEIVE_DISTANCE,
                params: {
                    message: 'locateFailed'
                }
            }
            window.postMessage(JSON.stringify(a1));
            clearInterval(timer);
            timer = null;
        }
    }
}, 200);
var pos;
var inArea;
var isError;
var api = {
    base_host: 'https://test-vmbase.scn.weilian.cn',
    customer_host: 'https://test-vmcustomer.scn.weilian.cn',
    // base_host: 'https://pre-vmbase.scn.weilian.cn',
    // customer_host: 'https://pre-vmcustomer.scn.weilian.cn',
    // base_host: 'https://vmbase.scn.weilian.cn',
    // customer_host: 'https://vmcustomer.scn.weilian.cn',
}
var MessageParams = {
    RECEIVE_STORE: 'receiveStore',
    RECEIVE_DISTANCE: 'receiveDistance',
}
//开启高德地图
var map = new AMap.Map('allmap', {});
//门店列表
var storeList = [];
//是否获取到门店列表的状态，默认false
var storeListStatus = 0;
//当前定位位置
var currentPos;
//倒计时变量
var countDown;
//获取门店列表
function getStoreList() {
    $.ajax({
        url: api.base_host + '/baseStore/getRestStore',
        type: 'get',
        success: function(res) {
            res.returnCode && (storeList = res.data[0]);
            res.returnCode && (storeListStatus = 1);
        },
        error: function(err) {
            console.log(err,'errrrrr');
        }
    })
}
//根据经纬度计算距离，单位是千米
function calculate(lat1, lng1, lat2, lng2) {
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    return s
};
//计算到门店的距离并添加到门店列表中
function calculateDistance(res) {
    storeListStatus ? sendToRn(res) : setTimeout(calculateDistance.bind(null, res), 300);
}
//计算距离并发送给Rn
function sendToRn(res) {
    storeList.forEach(function(ele) {
        //计算到门店距离
        (ele.positionLng && ele.positionLat) 
            ? ele.distance = calculate(ele.positionLat, ele.positionLng, res.position.lat, res.position.lng).toFixed(2) 
            : ele.distance = 0;
    })
    for(let i = 0;i < storeList.length;i++) {
        for(let j = i + 1;j < storeList.length;j++){
            if(storeList[i].distance < storeList[j].distance) {
                let temp = storeList[i];
                storeList[i] = storeList[j];
                storeList[j] = temp;
            }
        }
    }
    storeList = storeList.reverse();
    let zeroArr = [];
    let countArr = [];
    storeList.forEach(function(ele) {
        ele.distance == 0 ? zeroArr.push(ele) : countArr.push(ele);
    })
    storeList = countArr.concat(zeroArr);
    //发送带有距离的门店地址给RN
    pos = storeList;
}
//计算是否在门店配送范围内
function calculateInArea(res) {
    $.ajax({
        url: api.customer_host + '/address/getTMS',
        type: 'get',
        data: {
            longitudeandlatitude: res.position.lng + ',' + res.position.lat
        },
        success: function(res) {
            console.log(res.data[0], 'zaibuzaiya');
            if(res.returnCode) {
                inArea = res.data[0]
            }else {
                inArea = 'unmatch'
            }
        },
        error: function(err) {
            console.log(err,'errrrrr');
        }
    })
};
//定位
function getLocation() {
    map.plugin(['AMap.Geolocation'], function() {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,               //是否使用高精度定位，默认:true
            timeout: 10000,                          //超过5秒后停止定位，默认：无穷大
            maximumAge: 0,                          //定位结果缓存0毫秒，默认：0
        });
        //计时5s，防止超时未调用err函数
        countDown = setTimeout(function() {
            isError = true;
        }, 5000);
        //开始定位
        geolocation.getCurrentPosition();
        //定位成功
        geolocation.on('complete', function (res) {
            clearTimeout(countDown);
            countDown = null;
            //当前定位位置
            currentPos = res;
            //计算到门店的距离
            calculateDistance(res);
            //计算是否在门店配送范围内
            calculateInArea(res);
        });
        //定位失败
        geolocation.on('error', function (err) {
            console.log(err)
            isError = true;
        });
    })
}
//调用函数
getStoreList();
getLocation();
